package com.chenc.javathreads.controlleraop.signutil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;

/**
 * @ClassName
 * @Describtion:
 * @Author:Chenc
 * @Date:2023/12/30 22:39
 * @Version 1.0
 */
public class CaiNiaoSignUtil {

    public static String sign(String body, String secret) {
        if (StringUtils.isNotEmpty(body)) {
            String content = sortJson(new JSONObject(body)) + "&" + secret;
            return DigestUtils.md5DigestAsHex(content.getBytes());
        } else {
            return DigestUtils.md5DigestAsHex(secret.getBytes());
        }
    }

    public static String sortJson(JSONObject json) {
        List<String> keys = new ArrayList<>();
        keys.addAll(json.keySet());
        Collections.sort(keys);
        StringJoiner joiner = new StringJoiner("&");
        for (String key : keys) {
            Object value = json.get(key);
            if (value instanceof JSONArray) {
                joiner.add(sortJsonArray(key, (JSONArray) value));
            } else if (value instanceof JSONObject) {
                joiner.add(sortJson((JSONObject) value));
            } else {
                joiner.add(key + "=" + value);
            }
        }
        return joiner.toString();
    }


    public static String sortJsonArray(String key, JSONArray array) {
        List<String> values = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                values.add(sortJsonArray(key, (JSONArray) value));
            } else if (value instanceof JSONObject) {
                values.add(sortJson((JSONObject) value));
            } else {
                values.add(value.toString());
            }
        }
        Collections.sort(values);
        return key + "=" + String.join(",", values);
    }

    public static void main(String[] args) {
        String body = "{\"b\":2,\"a\":1,\"c\":{\"x\":3,\"y\":[2,1]},\"d\":[{\"z\":5}, {\"z\":4},{\"z\":null}]}";
        String secret = "edi";
        System.out.println("\n原json：");
        System.out.println(body);

        System.out.println("\n排序并拼接结果：");
        System.out.println(sortJson(new JSONObject(body)) + "&" + secret);

        System.out.println("\n签名如下：");
        String sign = sign(body, secret);
        System.out.println(sign);

    }

}
